import csv
import os
import sys
import time
from originJScrash import OriginJScrash
from readFile import ReadFile


class WriteFile(object):

    @staticmethod
    def sortInst(file_path):
        listcontents = ReadFile.readFile(file_path, word='jscrash')
        dict_mod_insts = {}
        dict_final = {}
        for contents in listcontents:
            inst = OriginJScrash(contents)
            if inst.crucial:
                k_mod = ("关键进程/应用" + str(inst.module_name), inst.stacktrace)
            else:
                k_mod = (str(inst.module_name), inst.stacktrace)
            v_inst = inst
            if k_mod in dict_mod_insts:
                dict_mod_insts[k_mod].append(v_inst)
            else:
                dict_mod_insts[k_mod] = [v_inst]
        for mod in dict_mod_insts:
            dict_stack_path = {}
            inst_list = dict_mod_insts[mod]
            for inst in inst_list:
                k_stack = inst.stacktrace
                v_path = inst.path
                if k_stack in dict_stack_path:
                    dict_stack_path[k_stack].append(v_path)
                else:
                    dict_stack_path[k_stack] = [v_path]
            dict_final[mod] = dict_stack_path
        return dict_final

    @staticmethod
    def write(jsdir):
        '''
        comment: write result to txt and csv
        :param cppdir:
        :param basis_inst:
        :return:
        '''
        all_info = WriteFile.sortInst(jsdir)
        now = time.strftime('%Y%m%d%H%M%S')
        if os.path.isfile(jsdir):
            jsdir = os.path.split(jsdir)[0]
        txt_path = os.path.join(jsdir, f"ResultOfJscrash{now}.txt")
        csv_path = os.path.join(jsdir, f"ResultOfJscrash{now}.csv")
        WriteFile.writetxt(txt_path, all_info)
        WriteFile.writecsv(csv_path, all_info)

    @staticmethod
    def writetxt(txt_path, all_info):
        description = ['模块名: ', '栈名: ', '出现次数: ', '文件路径: ']
        with open(txt_path, 'w', encoding='utf-8-sig') as fw:
            for cont in all_info:
                if cont == None:
                    pass
                else:
                    for k_stack, v_path in all_info[cont].items():
                        contents = [cont[0], k_stack, len(v_path), '\n'.join(v_path)]
                        for i in range(len(description)):
                            so_pri_info = description[i] + str(contents[i])
                            fw.write(so_pri_info + '\n')
                fw.write('\n')
        fw.close()
        print('txt_path: ', txt_path)

    @staticmethod
    def writecsv(csv_path, all_info):
        with open(csv_path, "w", newline="", encoding='utf-8-sig') as fcsv:
            writer = csv.writer(fcsv)
            writer.writerow(['模块名', '栈名', '出现次数', '文件路径'])
            for cont in all_info:
                for k_stack, v_path in all_info[cont].items():
                    contents = [cont, k_stack, len(v_path), str(v_path[0])]
                    writer.writerow(contents)
        fcsv.close()
        print('csv_path: ', csv_path)

    @staticmethod
    def mainOfJscrash(file_path):
        WriteFile.write(file_path)


if __name__ == '__main__':
    argv = sys.argv
    version = 'VERSION: 2022_04_18'
    if len(argv) != 2:  # 判断元素个数
        print("usage: python jscrashParser.py dir")
    else:
        if argv[1] == '-v':
            print(version)
        else:
            print(version)
            WriteFile.mainOfJscrash(argv[1])
